package logic

import (
	"context"
	"fmt"
	"gite/giterpc/giterpc"
	"gite/giterpc/internal/svc"
	"gite/models"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogic {
	return &AddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddLogic) Add(in *giterpc.AddRequest) (*giterpc.AddResponse, error) {
	// todo: add your logic here and delete this line

	if in.Address == "" {
		return nil, fmt.Errorf("有必填项未填写")
	}

	var giter models.Gite
	models.DB.Debug().Where("name = ?", in.Name).Find(&giter)
	if giter.ID != 0 {
		return nil, fmt.Errorf("当前仓库已存在")
	}

	giter = models.Gite{
		Name:    in.Name,
		Address: in.Address,
	}
	models.DB.Debug().Create(&giter)

	return &giterpc.AddResponse{
		GiteId: int64(giter.ID),
	}, nil
}
